/**
 * @FileName: TokenService.java
 * @Author
 * @Description:
 * @Date 2016年1月4日 下午1:29:18
 * @CopyRight ZTE Corporation
 */
package cn.hpclub.server.service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;

import cn.hpclub.server.model.MemberOrg;
import cn.hpclub.server.model.Token;
import cn.hpclub.server.util.SystemConfigUtil;

public class TokenService{
    public static TokenService  service = new TokenService();
    private static final Logger logger  = LoggerFactory.getLogger(TokenService.class);

    private String generateToken(String username){
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String curTime = sdf.format(date);
        return curTime + username;
    }

    private boolean writeToken(String username, String tokenString){

        Token token = Token.dao.getTokenByUserName(username);
        if(token == null){
            Record record = new Record();
            record.set("username", username);
            record.set("token", tokenString);
            record.set("login_time", new Date());
            boolean success = Db.save("user_token_map", "id", record);
            if(!success){
                return false;
            }

        } else{
            token.set("token", tokenString);
            token.set("login_time", new Date());
            boolean update = token.update();
            if(!update){
                return false;
            }
        }

        return true;
    }

    public String getToken(String username){
        String oldToken = getAndExpandTokenIfActive(username);
        if((oldToken == null) || ("".equals(oldToken))){
            return writeNewToken(username);
        }
        return removeBlankspace(oldToken);
    }

    /**
     * @Title: checkToken
     * @Description:TODO
     * @param token
     * @return String
     */

    private String removeBlankspace(String token){
        if(token.contains(" ")){
            logger.error("Error:token has blank space, remove blank space." + token);
            token = token.replace(" ", "");
        }
        return token;
    }

    private String writeNewToken(String username){
        String token = generateToken(username);
        token = removeBlankspace(token);
        boolean success = writeToken(username, token);
        if(success){
            return token;
        }
        return "";
    }

    /**
     * @Title: getTokenIfActive
     * @Description:如果token还在有效期内，再次登陆，则直接返回token并延长其使用时间
     * @param username
     * @return null,""--没有有效token;token，当前token仍有效，进行时间扩展
     */
    private String getAndExpandTokenIfActive(String username){
        if((username == null) || ("".equals(username))){
            return null;
        }

        Token token = Token.dao.getTokenByUserName(username);
        if(token == null){
            // 不存在，没有登陆过
            return null;
        }

        int expireMin = SystemConfigUtil.getSystemConfig().getTokenExpireTime();
        long date1 = new Date().getTime(); // 当前时间
        long loginTime = token.getDate(Token.LOGIN_TIME).getTime();
        long diff = date1 - loginTime; // 毫秒为单位
        long expireMSecond = (long)expireMin * 60 * 1000;
        if((diff >= -(60 * 60 * 1000)) && (diff <= expireMSecond)){
            // 有效期内
            token.set("login_time", new Date());
            boolean update = token.update();
            if(update){
                String tokenString = token.getStr(Token.TOKEN);
                return tokenString == null ? "" : tokenString;
            }
            return null;

        }
        return null;
    }

    public boolean validate(String tokenStr){
        // 合法并且没有超期，则token验证成功，否则认为是没有登陆，返回1009
        if(isTokenLegal(tokenStr) && (isTokenActive(tokenStr))){
            return true;
        }
        return false;

    }

    public boolean isTokenActive(String tokenStr){
        if((tokenStr == null) || (tokenStr.equals(""))){
            return false;
        }
        int expireMin = SystemConfigUtil.getSystemConfig().getTokenExpireTime();
        long date1 = new Date().getTime(); // 当前时间
        long date2 = Token.dao.getLoginTime(tokenStr); // 登录时间
        long diff = date1 - date2; // 毫秒为单位
        long expireMSecond = (long)expireMin * 60 * 1000;
        if((diff >= -(60 * 60 * 1000)) && (diff <= expireMSecond)){
            return true;
        }
        return false;
    }

    public boolean isTokenLegal(String tokenStr){
        if((tokenStr == null) || (tokenStr.equals("")) || (tokenStr.length() <= 11)){
            return false;
        }
        String username = Token.dao.getNotExpiredUsernameByToken(tokenStr);
        String usernameInToken = tokenStr.substring(tokenStr.length() - 11, tokenStr.length());
        if((username != null) && (username.equals(usernameInToken))){
            return true;
        }
        logger.error("token illegal,usernameInToken:'" + usernameInToken + "',usernameInDb:'" + username + "'");
        return false;
    }

    public int getOrgIdFromToken(String token){
        return Token.dao.getOrgIdByToken(token);
    }

    public String getUsernameByToken(String token){
        return Token.dao.getUsernameByToken(token);
    }

    public long getTime(String time) throws ParseException{
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        Date d;
        d = sdf.parse(time);
        long l = d.getTime();
        return l;

    }

    /**
     * @Title: getMemberOrgInfoByToken
     * @Description:TODO
     * @param token
     * @return Record
     */
    public Record getMemberOrgInfoByToken(String token){
        return MemberOrg.dao.getMemberOrgInfoByToken(token);
    }

    public String getTokenByUserid(int userid){
        return Token.dao.getTokenByUserid(userid);
    }

}
